package algorithm.dynamic;

import java.util.Arrays;

/**
 * 322. Coin Change
 * leetcode: https://leetcode.com/problems/coin-change/
 * Difficulty: Medium
 *
 * 题解: 动态规划多重背包问题
 * https://leetcode.com/problems/coin-change/solution/
 *
 * Created by yzy on 2019-03-25 15:57
 */
public class CoinChange {

    public static void main(String[] args) {
        int[] coins = new int[]{1,2,5};
        int amount = 11;
        System.out.println(coinChange(coins, amount));
    }


    /**
     * dp[i] 表示 amount=i 时，需要的最小硬币数
     *
     * @param coins
     * @param amount
     * @return
     */
    public static int coinChange(int[] coins, int amount){
        int max = amount+1;
        int[] dp = new int[max];
        Arrays.fill(dp, max);   // 默认填最大值
        dp[0] = 0;              // amount=0时，需要的硬币数为0

        for(int i=1; i<=amount; i++){
            for(int j=0; j<coins.length; j++){
                if(coins[j] <= i){  // 只有当前硬币面值小于amount，才有计算的价值。
                    dp[i] = Math.min(dp[i], dp[i-coins[j]]+1);
                }
            }
        }

        return dp[amount] > amount ? -1 : dp[amount];
    }

}
